package com.TLLT.QADMobileItemEnquiry;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DataDataSource {

	// Database fields
	private SQLiteDatabase database;
	private DataBase dbHelper;
	private String[] allColumns = { DataBase.COLUMN_ID,
			DataBase.COLUMN_COMMENT };

	public DataDataSource(Context context) {
		dbHelper = new DataBase(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Table createTable(String data) {
		ContentValues values = new ContentValues();
		values.put(DataBase.COLUMN_COMMENT, data);
		long insertId = database.insert(DataBase.TABLE_COMMENTS, null,
				values);
		// To show how to query
		Cursor cursor = database.query(DataBase.TABLE_COMMENTS,
				allColumns, DataBase.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		return cursorToComment(cursor);
	}
	
	public void updateTable(String rowId,String data) {
		ContentValues args = new ContentValues();
	    args.put(DataBase.COLUMN_COMMENT, data);
	    database.update(DataBase.TABLE_COMMENTS, args, DataBase.COLUMN_ID + "=" + rowId, null);
	}
	
	public Table getTable(String rowId) {
		Cursor cursor = database.query(DataBase.TABLE_COMMENTS,
				allColumns, DataBase.COLUMN_ID + " = " + rowId, null,
				null, null, null);
		cursor.moveToFirst();
		return cursorToComment(cursor);
	}

	public void deleteTable(Table data) {
		long id = data.getId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(DataBase.TABLE_COMMENTS, DataBase.COLUMN_ID
				+ " = " + id, null);
	}

	public List<Table> getAllTable() {
		List<Table> lines = new ArrayList<Table>();
		Cursor cursor = database.query(DataBase.TABLE_COMMENTS,
				allColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Table line = cursorToComment(cursor);
			lines.add(line);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return lines;
	}

	private Table cursorToComment(Cursor cursor) {
		Table comment = new Table();
		comment.setId(cursor.getLong(0));
		comment.setData(cursor.getString(1));
		return comment;
	}
}
